#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "uorc/uorc.h"

/* Example program that turns off/on the laserpointer */

// ensure laser is off and memory freed at exit
static void cleanup(int s, void *arg)
{
    uorc_t *uorc = (uorc_t *)arg;
    uorc_digital_set_value(uorc, 0, 0);
    uorc_destroy(uorc);
    printf("done\n");
}

static void sighandler(int s)
{
	switch(s) {
        case SIGQUIT:
        case SIGINT:
        case SIGTERM:
            printf("Exiting...");
            exit(0);
        default:
            break;
	}
}

int main(int argc, char *argv[])
{
    ///// uorc /////
    uorc_t *uorc = uorc_create();
    if (uorc == NULL) {
        printf("ERR: Could not create orc\nExiting...\n");
        exit(-1);
    }
    int val = 0;

    ///// Signal handling /////
    // want to ensure that if process terminats (e.g. <ctrl-C>) the laser is turned off
	on_exit(cleanup, uorc);
	signal(SIGINT, sighandler);
	signal(SIGQUIT, sighandler);
	signal(SIGTERM, sighandler);

    // set digital I/O pin to output mode
    uorc_digital_make_output_pin(uorc, 0);

    while(1) {
        usleep(1000000);
        uorc_digital_set_value(uorc, 0, val);  // set output value (0, 1)
        printf("%s\n", (val ? "on" : "off"));

        val = (val + 1) % 2;
    }
}
